package com.ruoyi.socket.probuffer;


import com.google.common.base.Throwables;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;

public class ProtoServerHandler extends SimpleChannelInboundHandler<DataInfo.DeviceData> {

    private static Logger logger = LoggerFactory.getLogger(ProtoServerHandler.class);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DataInfo.DeviceData msg) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();
        logger.info(" 读取channel byte{}", ByteBufUtil.hexDump(buffer));
        System.out.println("读取channel byte " + ByteBufUtil.hexDump(buffer));
        Channel channel = ctx.channel();
        ChannelId id = channel.id();
        System.out.println("id " + id);
        SocketAddress socketAddress = channel.unsafe().remoteAddress();
        System.out.println(socketAddress);


        // todo 处理接收到数据的处理逻辑
        String content = msg.getContent().toStringUtf8();
        String uft_Content = new String(content.getBytes(), "UTF-8");
        System.out.println("uft_Content " + uft_Content);
        //设备情况
        String deviceID = msg.getDeviceID();
        String deviceName = msg.getDeviceName();
        String devicetype = msg.getDevicetype();
        System.out.println("deviceName " + deviceName);

        // 数据
        String controlMsg = msg.getControlMsg();
        System.out.println("controlMsg " + controlMsg);

        String gateInfo = msg.getGateInfo();
        String gatewayID = msg.getGatewayID();
        System.out.println("gateInfo " + gateInfo);
        ctx.channel().writeAndFlush(msg);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.out.println(Throwables.getStackTraceAsString(cause));
        logger.error("exceptionCaught {}", Throwables.getStackTraceAsString(cause));
        ctx.fireExceptionCaught(cause);

    }


}